# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
话单月结(线路商)
"""
from util import (
    logging,
    query_es,
    get_month_time_scale,
    date_slice,
    time,
    ms2min,
    write_excel,
    Elasticsearch,
    es_ip,
    es_port,
    excel_save_dir,
)


class ExportMonthlyBillsByLine:
    def __init__(self, ui_data):
        self.data_date = ui_data["data_date"]
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        self.call_type = ui_data.get("call_type")
        company_id = ui_data.get("company_id")
        db_name = f"yicall_{company_id}"
        table_index = ui_data.get("business_id")
        self.es = Elasticsearch(hosts=es_ip, port=es_port)
        if self.call_type == "呼出":
            self.es_index = (
                f"{db_name}_{table_index}_callout_session_ach_{self.data_date}"
            )
        else:
            self.es_index = (
                f"{db_name}_{table_index}_callout_session_in_ach_{self.data_date}"
            )

    def query_es_data(self, day_start_time, day_end_time):
        """"""
        body = {
            "query": {
                "bool": {
                    "must": [
                        {"term": {"calloutConnectStatus": 100}},
                        {
                            "range": {
                                "calloutFinishTime": {
                                    "gte": day_start_time,
                                    "lte": day_end_time,
                                }
                            }
                        },
                    ]
                }
            }
        }
        fields = ["calloutDialNumber", "dialogDuration"]
        day_es_data = query_es(self.es_index, body, fields)
        return day_es_data

    def export(self):
        bill_info = dict()  # 总账单信息
        # 以“天”为单位查询es数据，避免scroll超时
        month_start_time, month_end_time = get_month_time_scale(self.data_date)
        date_slice_result = date_slice(month_start_time, month_end_time)
        handle_data_start_time = time.time()
        for everyday in date_slice_result:
            day_start_time = everyday[0]
            day_end_time = everyday[1]
            es_data = self.query_es_data(day_start_time, day_end_time)
            for data in es_data:
                line_number = data.get("calloutDialNumber")
                dialog_duration_ms = data.get("dialogDuration")
                dialog_duration_min = ms2min(int(dialog_duration_ms))
                find_task_data = bill_info.get(line_number, None)
                if find_task_data is None:
                    bill_info[line_number] = dialog_duration_min
                else:
                    bill_info[line_number] += dialog_duration_min
        handle_data_end_time = time.time()
        handle_data_take_time = handle_data_end_time - handle_data_start_time
        logging.info(
            f"处理从ElasticSearch中查询出来的数据共计耗时{handle_data_take_time:.2f}秒。"
        )
        if bool(bill_info) is False:
            msg = (
                f"<font color=green>无法导出“{self.business}”的【{self.data_type}】，"
                f"原因：\n在{month_start_time}至{month_end_time}没有{self.call_type}数据！</font>"
            )
            logging.warning(msg)
            return {"code": 1, "excel_names": [], "msg": msg}
        else:
            if self.call_type == "呼出":
                excel_title = ["主叫号码", "通话时长(分)"]
            else:
                excel_title = ["被叫号码", "通话时长(分)"]
            excel_data = bill_info.items()
            file_name = (
                f"{self.business}_({self.call_type}){self.data_type}_{self.data_date}"
            )
            write_excel_start_time = time.time()
            excel_name = write_excel(
                [[self.data_type, excel_title, excel_data]], excel_save_dir, file_name
            )
            write_excel_end_time = time.time()
            write_excel_take_time = write_excel_end_time - write_excel_start_time
            logging.info(
                f"将{self.business}的{self.data_type}写入excel共计耗时{write_excel_take_time:.2f}秒。"
            )
            return {"code": 0, "excel_names": [excel_name], "msg": None}


if __name__ == "__main__":
    ...
